package org.example.database.service.impl;

import org.example.database.DTO.UserLoginDTO;
import org.example.database.DTO.UserRegisterDTO;
import org.example.database.Mapper.UserMapper;
import org.example.database.entity.User;

import org.example.database.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register( UserRegisterDTO userRegisterDTO) {
        // 1. 数据校验
        if (userRegisterDTO.getAccountNumber() == null || userRegisterDTO.getPassword() == null) {
            throw new IllegalArgumentException("账号和密码不能为空");
        }
        
        // 验证用户类型是否有效
        String userType = userRegisterDTO.getUserType();
        if (userType == null) {
            throw new IllegalArgumentException("用户类型不能为空");
        }
        userType = userType.toLowerCase();

        if (!("student".equals(userType) || "teacher".equals(userType) || "hr".equals(userType))) {
            throw new IllegalArgumentException("无效的用户类型，只能是student、teacher或hr");
        }

        User user = new User();
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setCreationTime(LocalDateTime.now());
        user.setModificationTime(LocalDateTime.now());

        // 3. 插入数据
        userMapper.insert(user);
    }

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        // 1. 数据校验
        if (userLoginDTO.getAccountNumber() == null || userLoginDTO.getPassword() == null) {
           throw new IllegalArgumentException("账号和密码不能为空");
        }

        // 2. 根据账号查询用户
        User user = userMapper.findByAccountNumber(userLoginDTO.getAccountNumber());
        if (user == null) {
           throw new IllegalArgumentException("用户不存在");
        }

        // 3. 密码比对
        if (!user.getPassword().equals(userLoginDTO.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }
        return user;
    }
}